package com.tbl.common.config;

import com.tbl.common.utils.StringUtils;
import com.tbl.common.utils.YamlConfigurerUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.util.Properties;

/**
 * 获取yml配置（区分生产环境和测试环境）
 * @author 70486
 * @date 2020/5/1
 */
@Configuration
public class BeanConfiguration {
    private final Logger logger = LoggerFactory.getLogger(BeanConfiguration.class);
    @Bean
    public YamlConfigurerUtil ymlConfigurerUtil() {
        //1:加载配置文件
        Resource app = new ClassPathResource("/application.yml");
        Resource appDataSourceDev = new ClassPathResource("/application-dev.yml");
        Resource appDataSourceTest = new ClassPathResource("/application-test.yml");
        YamlPropertiesFactoryBean yamlPropertiesFactoryBean = new YamlPropertiesFactoryBean();
        // 2:将加载的配置文件交给 YamlPropertiesFactoryBean
        yamlPropertiesFactoryBean.setResources(app);
        // 3：将yml转换成 key：val
        Properties properties = yamlPropertiesFactoryBean.getObject();
        //在配置文件中获取
        String active = properties != null ? properties.getProperty("spring.profiles.active") : null;

        //判断当前配置是什么环境
        if (StringUtils.isBlank(active)) {
            logger.error("未找到spring.profiles.active配置！");
        }else {
            //测试环境
            if ("test".equals(active)) {
                yamlPropertiesFactoryBean.setResources(app,appDataSourceTest);
            }else if("dev".equals(active)){
                //正式环境
                yamlPropertiesFactoryBean.setResources(app,appDataSourceDev);
            }
        }
        // 4: 将Properties 通过构造方法交给我们写的工具类
        return new YamlConfigurerUtil(yamlPropertiesFactoryBean.getObject());
    }
}
